package com.tandashi.springbootstudy01.study.clone;

import java.io.*;

/**
 * 深拷贝：利用序列化来实现，所以对应的实体类需要实现Serializable
 * 主要是 Person 下的Address 对象引用，深拷贝的话会拷贝一个新的Address 对象，不是直接引用原来的Address
 * 利用序列化的好处就是，对对象的引用不需要在重写clone()方法，比如Person 引用了Address 对应，如果Address再引用其他的对象
 * 还需要再手动实现Cloneable,复写clone()方法
 */
public class DeepClone {
    public static void main(String[] args) throws IOException, ClassNotFoundException {

        Person person = new Person("zhangsan",18);
        Address address = new Address("山西省","霍州市");
        person.setAddress(address);

        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bao);
        oos.writeObject(person);
        System.out.println("before set Address person="+person);

        address.setCity("太原市");
        person.setAddress(address);
        System.out.println("after set Address person="+person);

        ByteArrayInputStream bai = new ByteArrayInputStream(bao.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bai);
        Person person1 = (Person)ois.readObject();
        System.out.println("deep clone person1="+person1);
    }
}
